package com.itheima.reggie.filter;


import com.alibaba.fastjson.JSON;

import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//过滤器
/*A. 获取本次请求的URI
B. 判断本次请求, 是否需要登录, 才可以访问
C. 如果不需要，则直接放行
D. 判断登录状态，如果已登录，则直接放行
E. 如果未登录, 则返回未登录结果
*/
@Slf4j
@WebFilter(urlPatterns = "/*", filterName = "LoginCheckFilter")
public class LoginCheckFilter implements Filter {
    //路径校验工具
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //将servletRequest和servletResponse转换为request和response
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取本次请求的URI
        String currentUri = request.getRequestURI();
        log.info("拦截到的请求，uri：{}", currentUri);
        //2.判断本次请求是否需要处理，哪些请求不需要处理，登录，登出，静态资源
        String[] uris = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //遍历比对uri
        //3.如果不需要，则直接放行
        boolean flag = extracted(currentUri, uris); //flag为true，就是匹配到，放行
        if (flag) {
            log.info("当前请求无需处理，uri:{}", currentUri);
            //接收的uri符号不需要处理的请求，放行
            filterChain.doFilter(request, response);
            return;
        }
        //4. 判断登录状态，如果已登录，则直接放行,在session中查找id
        Long employeeId = (Long) request.getSession().getAttribute("employee");
        if (employeeId != null) {
            log.info("用户已登录，放行，uri:{}", currentUri);
            //把当前登录用户设置到本地线程中
            BaseContext.setCurrentId(employeeId);
            filterChain.doFilter(request, response);
            return;
        }
        //4.1. 判断移动端用户登录状态，如果已登录，则直接放行,在session中查找id
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null) {
            log.info("用户已登录，放行，uri:{}", currentUri);
            //把当前登录用户设置到本地线程中
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }
        //5. 如果未登录, 则返回未登录结果
        log.warn("用户未登录，请先登录，uri:{}", currentUri);
        R<Object> notlogin = R.error("NOTLOGIN");
        response.getWriter().write(JSON.toJSONString(notlogin));
    }
    private boolean extracted(String currentUri, String[] uris) {
        for (String uri : uris) {
            if (ANT_PATH_MATCHER.match(uri, currentUri)) {
                return true;
            }
        }
        return false;
    }
}
